<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Encore\Admin\Traits\AdminBuilder;
use Encore\Admin\Traits\ModelTree;
use DB;

class Category extends Model
{
    use AdminBuilder, ModelTree;

    protected $fillable = [
        'title',
        'parent_id',
        'deleted',
        'logo',
        'order',
        'book_total'
    ];

    //https://segmentfault.com/a/1190000015258789
    public static function getSelectOptions()
    {
        $options = DB::table('categories')->where('deleted',0)->where('parent_id',0)->select('id','title as text')->get();
        //$selectOption[0] = '请选择';
        if(!empty($options))
        {
            $selectOption[0] = '请选择';
            foreach ($options as $option){
                $selectOption[$option->id] = $option->text;
            }
        }
        else
        {
            $selectOption[] = ['请选择'];
        }

        return $selectOption;
    }

    public static function getSecondSelectOptions($category_id = 0)
    {

        if(!empty($category_id))
        {
            $category = DB::table('categories')->where('id',$category_id)->select('id','title as text','parent_id')->first();
            $options = DB::table('categories')->where('deleted',0)->where('parent_id',$category->parent_id)->select('id','title as text')->get();
            $selectOption = [];
            foreach ($options as $option){
                $selectOption[$option->id] = $option->text;
            }
        }
        else
        {
            $selectOption = [
                [
                    'id' => 0,
                    'text' => '请选择'
                ]
            ];
        }

        return $selectOption;
    }

    public function scopeNotDeleted()
    {
        return $this->where('deleted', 0);
    }

    public static function options($id)
    {
        if (! $self = static::find($id)) {
            return [];
        }

        return $self->brothers()->where('deleted',0)->pluck('title', 'id');
    }

    public function parent()
    {
        return $this->belongsTo(Category::class, 'parent_id');
    }

    public function children()
    {
        return $this->hasMany(Category::class, 'parent_id');
    }

    public function brothers()
    {
        return $this->parent->children();
    }

    //脚本同步分类下书数量
    public static function calculateBookTotal()
    {
        $list = static::query()->where('parent_id',0)->where('deleted',0)->get();
        if(!empty($list))
        {
            foreach ($list as $v)
            {
                $book_total = Book::query()->where('deleted',0)->where('category_parent_id',$v->id)->count();
                static::where('id',$v->id)->update([
                    'book_total' => $book_total
                ]);
            }
        }
    }
}
